'use strict';
const assert = require('assert');

/**
 * 頻率限制 是
 * @param {{routerName: String,freq:  Number,cycle: Number}}  路由名 每个周期的请求频率 周期（秒）
 * @return {Method} middleware
 */
module.exports = ({ routerName, freq = 5, cycle = 60 }) => {
  assert(routerName, 'routerName required');
  return async (ctx, next) => {
    const time = await ctx.app.redis.incr(`frequencelimit:${routerName}:${ctx.ip}`, cycle);
    if (time > freq) {
      ctx.body = 'frequence limit';
      return;
    }
    await next();
  };
};
